package com.qiaofang.applet.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.constant.CommonConstant;
import com.qiaofang.applet.common.constant.ResponseCode;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * 用户登陆验证过滤器
 * @author QF2019
 */
@Slf4j
@Component
public class AuthFilter extends GenericFilterBean {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        // 验证token
        boolean succ = resolveToken((HttpServletRequest) servletRequest);
        // 验证不通过，直接返回401
        if(!succ){
            writeResponse((HttpServletResponse)servletResponse);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * token验证
     *
     * @param request
     * @return
     */
    private boolean resolveToken(HttpServletRequest request) {
        String token = "";
        try {
            token = CookieUtil.getToken(request);
        } catch (Exception e) {
            log.error("获取token失败", e);
        }
        if(StringUtils.isBlank(token)) {
            return false;
        }
        // 测试环境写死
//        if(StringUtils.equals("TEST_TOKEN", token)){
//            return true;
//        }
        String tokenKey = RedisKeyUtil.getPcWebTokenKey(token);
        if(!redisTemplate.hasKey(tokenKey)){
            return false;
        }

        // 刷新token过期时间
        //redisTemplate.expire(tokenKey, CommonConstant.TOKEN_TIMEOUT, TimeUnit.MILLISECONDS);
        return true;
    }

    /**
     * 输出响应结果
     * @param response
     * @throws IOException
     */
    private void writeResponse(HttpServletResponse response) throws IOException {
        DataResponse dataResponse = DataResponse.fail(ResponseCode.LOGIN_AUTH_FAIL.getStatus(), ResponseCode.LOGIN_AUTH_FAIL.getMessage());
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(dataResponse));
        //response.setStatus(ResponseCode.LOGIN_AUTH_FAIL.getStatus());
    }
}
